<template>
  <el-select
    v-model="comValue"
    :multiple="multiple"
    collapse-tags-tooltip
    placeholder="请选择"
    style="width: 240px"
    :disabled="disabled"
    filterable
    clearable
  >
    <el-checkbox
      v-if="props.hasSelectAll"
      style="margin-left: 20px"
      v-model="isSelectAll"
      @change="selectAll"
    >
      全选
    </el-checkbox>
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>
<script setup>
import { ref, computed, onBeforeMount } from 'vue'
import {
  service_quality_tasks_getOrg,
  service_quality_tasks_getOrg2
} from '@/api/api'
import { prop } from 'dom7'

const emit = defineEmits([
  'update:modelValue',
  'update:name',
  'update:areaStr',
  'change',
  'typeChange'
])
const props = defineProps({
  hasSelectAll: {
    type: Boolean,
    default: false
  },
  orgType: {
    type: [Number, String],
    default: 2
  },
  needSub: {
    type: Boolean,
    default: false
  },
  areaStr: {
    type: String
  },
  name: {
    type: String
  },
  modelValue: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  }
})
const options = ref([])
const isSelectAll = ref(false)
const selectAll = flag => {
  if (flag) {
    let arr = []
    options.value.map(item => {
      arr.push(item.id)
    })
    emit('update:modelValue', arr.join())
  }else{
    emit('update:modelValue', '')
  }
}
const comValue = computed({
  get() {
    if (props.multiple) {
      if(props.modelValue){
        let count = props.modelValue.split(',').length
        if(count == options.value.length){
          isSelectAll.value = true
        }else{
          isSelectAll.value = false
        }
      }
      return props.modelValue ? props.modelValue.split(',') : []
    }
    return props.modelValue
  },
  set(val) {
    if (props.multiple) {
      emit('update:modelValue', val.join())
    } else {
      emit('update:modelValue', val)
      if (val) {
        let target = options.value.filter(item => item.id == val)[0]
        emit('typeChange', target.type)
        emit('update:name', target.name)
        emit('update:areaStr', target.belongArea)
        emit('change', target)
      }
    }
  }
})

onBeforeMount(async () => {
  let res
  if (props.orgType) {
    res = await service_quality_tasks_getOrg({ orgType: props.orgType, needSub:props.needSub }) // orgType：2养老机构 3社区机构 // needSub:false当前行政级别的直属机构 true获取当前行政级别直属机构及下属单位的机构
  } else {
    res = await service_quality_tasks_getOrg2() // 获取当前行政级别直属机构及下属单位的养老机构
  }

  options.value = res.data
})
</script>
<style lang="scss" scoped></style>
